﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Resources;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace myAlarm
{
    public partial class Form1 : QT.Windows.Shell.GlassForm
    {
        #region Attributes

        ImageList myImageList = null;
        System.Timers.Timer myTimer = null;
        object myObj = new object();

        private delegate QTListView myDeleGategetListView();
        private delegate void myDeleGatesetAlarm(string guid);
        private delegate void myDeleGateresetAlarm(string guid);
        private delegate void myDeleGatedelayAlarm(string guid);

        #endregion

        #region Form

        public Form1()
        {
            InitializeComponent();
            loadImage();

            ThreadPool.SetMaxThreads(10, 10);
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            loadData();

            myTimer = new System.Timers.Timer();
            myTimer.Interval = 1000;
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
            myTimer.Start();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            this.statusStrip1.BackColor = AeroColor;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            e.Cancel = true;
            string closeType="0";
            try
            {
                ResourceReader rr = new ResourceReader(Properties.Resources.ResourcesPath);
                IDictionaryEnumerator dict = rr.GetEnumerator();
                while (dict.MoveNext())
                {
                    if (dict.Key.ToString() == "CloseType")
                    {
                        closeType = dict.Value.ToString();
                        break;
                    }
                }
                rr.Close();
            }
            catch
            {
            }
            switch (closeType)
            {
                case "1":
                    this.WindowState = FormWindowState.Minimized;
                    this.Hide();
                    break;
                case "2":
                    e.Cancel = false;
                    break;
                default:
                    showCloseBox();
                    break;
            }
        }

        #endregion

        #region Event

        #region Button

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Task myTask = new Task("A", null);
            myTask.Owner = this;
            myTask.ShowDialog();
            myTask.Dispose();
        }

        #endregion

        #region Timer

        public void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (ListViewItem item in getListView().Items)
            {
                if (item.ImageIndex != 1) continue;
                if (item.Tag.ToString() == "0") continue;
                if (DateTime.Parse(item.SubItems[2].Text) > DateTime.Now) continue;

                item.Tag = "1";
                ThreadPool.QueueUserWorkItem(new WaitCallback(showAlarm),item.SubItems[4].Text);
            }
        }

        #endregion

        #region ToolStripMenuItem

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        #endregion

        #region notifyIcon

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        #endregion

        #region ListView

        private void lvList_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ListViewItem item = ((QTListView)sender).GetItemAt(e.X, e.Y);
                ListViewItem.ListViewSubItem portSubItem = item.GetSubItemAt(e.X, e.Y);
                int intColIndex = item.SubItems.IndexOf(portSubItem);//这个就是列索引了

                if (intColIndex == 3)
                {
                    Task myTask = new Task("V", item.SubItems[4].Text);
                    myTask.ShowDialog();
                    myTask.Dispose();
                }
            }
        }

        private void lvList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = ((QTListView)sender).GetItemAt(e.X, e.Y);
            switch (item.ImageIndex)
            {
                case 0:
                    item.ImageIndex = 1;
                    break;
                case 1:
                    item.ImageIndex = 2;
                    break;
                case 2:
                    item.ImageIndex = 1;
                    break;
                default:
                    break;
            }
        }

        #endregion

        #endregion

        #region Method

        private void loadImage()
        {
            myImageList = new ImageList();
            myImageList.ImageSize = new Size(24, 24);
            myImageList.Images.Add(Properties.Resources.heart);
            myImageList.Images.Add(Properties.Resources.play);
            myImageList.Images.Add(Properties.Resources.pause);
        }

        private void loadData()
        {
            try
            {
                string dataXml = Properties.Resources.XmlPath;
                XmlDocument doc = new XmlDocument();
                doc.Load(dataXml);
                XmlNodeList tasks = doc.SelectNodes("/root/list/task");

                this.lvList.LargeImageList = myImageList;
                this.lvList.SmallImageList = myImageList;
                foreach (XmlNode xn in tasks)
                {
                    ListViewItem item = new ListViewItem();
                    item.UseItemStyleForSubItems = false;
                    item.SubItems[0].Text = "";
                    item.SubItems.Add(xn.SelectSingleNode("title").InnerText);
                    item.SubItems.Add(xn.Attributes["time"].Value);
                    ListViewItem.ListViewSubItem sub = item.SubItems.Add("详细内容");
                    sub.ForeColor = Color.Blue;
                    item.SubItems.Add(xn.Attributes["guid"].Value);
                    item.Tag = "0";
                    item.ImageIndex = 0;
                    this.lvList.Items.Add(item);
                }
            }
            catch
            {
            }
        }

        private void showCloseBox()
        {
            CloseBox myCloseBox = new CloseBox();
            DialogResult dr= myCloseBox.ShowDialog();
            myCloseBox.Dispose();
            if(dr==DialogResult.OK) this.Close();
        }

        private void showAlarm(object guid)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Properties.Resources.XmlPath);
            XmlNode task = doc.SelectSingleNode("/root/list/task[@guid='" + guid.ToString() + "']");
            Alarm myAlarm = new Alarm(task.SelectSingleNode("title").InnerText, task.SelectSingleNode("content").InnerText, task.Attributes["time"].Value, task.SelectSingleNode("repeat").Attributes["type"].Value == "1" ? true : false);
            switch (myAlarm.ShowDialog())
            {
                case DialogResult.OK:
                    setAlarm(guid.ToString());
                    break;
                case DialogResult.Cancel:
                    resetAlarm(guid.ToString());
                    break;
                case DialogResult.Retry:
                default:
                    delayAlarm(guid.ToString());
                    break;
            }
        }

        private void setAlarm(string guid)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new myDeleGatesetAlarm(setAlarm), new object[] { guid });
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Properties.Resources.XmlPath);
                XmlNode task = doc.SelectSingleNode("/root/list/task[@guid='" + guid.ToString() + "']");

                if (task.SelectSingleNode("repeat").InnerText != "0")
                {
                    foreach (ListViewItem item in this.lvList.Items)
                    {
                        if (item.SubItems[4].Text == guid)
                        {
                            this.Tag = "0";
                            DateTime time = DateTime.Parse(item.SubItems[2].Text);
                            while (time > DateTime.Now)
                            {
                                if (task.SelectSingleNode("repeat").Attributes["type"].Value == "1") time = time.AddMinutes(int.Parse(task.SelectSingleNode("repeat").InnerText));
                                if (task.SelectSingleNode("repeat").Attributes["type"].Value == "2") time = time.AddHours(int.Parse(task.SelectSingleNode("repeat").InnerText));
                            }
                            item.SubItems[2].Text = time.ToString("HH:mm:ss");
                        }
                    }
                }
                else
                {
                    foreach (ListViewItem item in this.lvList.Items)
                    {
                        if (item.SubItems[4].Text == guid)
                        {
                            this.Tag = "0";
                            item.ImageIndex = 0;
                        }
                    }
                }
            }
        }

        private void resetAlarm(string guid)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new myDeleGateresetAlarm(resetAlarm), new object[] { guid });
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Properties.Resources.XmlPath);
                XmlNode task = doc.SelectSingleNode("/root/list/task[@guid='" + guid.ToString() + "']");

                if (task.SelectSingleNode("repeat").Attributes["type"].Value == "1")
                {
                    foreach (ListViewItem item in this.lvList.Items)
                    {
                        if (item.SubItems[4].Text == guid)
                        {
                            this.Tag = "0";
                            DateTime time = DateTime.Now.AddMinutes(int.Parse(task.SelectSingleNode("repeat").InnerText));
                            item.SubItems[2].Text = time.ToString("HH:mm:ss");
                        }
                    }
                }
                else
                {
                    foreach (ListViewItem item in this.lvList.Items)
                    {
                        if (item.SubItems[4].Text == guid)
                        {
                            this.Tag = "0";
                            item.ImageIndex = 0;
                        }
                    }
                }
            }
        }

        private void delayAlarm(string guid)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new myDeleGatedelayAlarm(delayAlarm), new object[] { guid });
            }
            else
            {
                foreach (ListViewItem item in this.lvList.Items)
                {
                    if (item.SubItems[4].Text == guid)
                    {
                        this.Tag = "0";
                        DateTime time = DateTime.Now.AddMinutes(5);
                        item.SubItems[2].Text = time.ToString("HH:mm:ss");
                    }
                }
            }
        }

        private QTListView getListView()
        {
            if (this.InvokeRequired)
            {
                return this.Invoke(new myDeleGategetListView(getListView)) as QTListView;
            }
            else
            {
                return this.lvList;
            }
        }

        public void showItem(ListViewItem item)
        {
            this.lvList.Items.Add(item);
        }

        #endregion

        private void modifyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.lvList.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要修改的记录");
                return;
            }
            if (this.lvList.SelectedItems.Count > 1)
            {
                MessageBox.Show("每次只能修改一条记录");
                return;
            }

            Task myTask = new Task("M", this.lvList.SelectedItems[0].SubItems[4].Text);
            myTask.Owner = this;
            myTask.ShowDialog();
            myTask.Dispose();
        }
    }
}
